<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>留言板</title>
    <style>
      .box {
        width: 300px;
        margin: 100px auto;
      }

      textarea {
        margin-right: 15px;
        vertical-align: bottom;
        resize: none;
        outline: none;
      }

      button {
        cursor: pointer;
      }

      /* 重置元素样式 */
      ul {
        margin: 0;
        padding: 0;
      }

      .list {
        margin-top: 20px;
        padding-right: 5px;
      }
      .list > li {
        background-color: #f7d7f3;
        padding: 3px 5px;
        margin-bottom: 15px;
        color: #fb1d03;
        font-size: 14px;
      }
      .list > li:last-child {
        margin-bottom: 0;
      }
      /* 设置 li 前面小圆点样式 */
      li::marker {
        color: #fb1d03;
      }
      .list > li > a {
        float: right;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <textarea cols="30" rows="6" placeholder="请输入留言内容"></textarea>
      <button class="addBtn">发布</button>

      <ul class="list"></ul>
    </div>

    <script>
      var text = document.querySelector('textarea');
      var addBtn = document.querySelector('.addBtn');
      var ulEle = document.querySelector('.list');

      addBtn.onclick = function () {
        if (text.value === '') {
          alert('请输入留言内容');
          text.focus();
        } else {
          var li = document.createElement('li');
          li.innerHTML = text.value + '<a href="javascript:;">删除</a>'; // 阻止链接跳转：javascript:;
          ulEle.insertBefore(li, ulEle.children[0]);
          // 清空文本域内容
          text.value = '';
          text.focus();

          // 移除子节点
          var as = document.querySelectorAll('a');
          for (var i = 0; i < as.length; i++) {
            as[i].onclick = function () {
              ulEle.removeChild(this.parentNode);
            };
          }
        }
      };
    </script>
  </body>
</html>
